// 定义用户小仓库
import { defineStore } from "pinia";
// 引入接口 
import { reqLogin, reqLoginOut, reqUserInfo } from '../../api/user'
// 引入接口返回的数据的ts类型
import { loginFormData, loginResponseData, UserInfoResponseData } from '../../api/user/type'
import { UserState } from './types/type'
// 引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'
import { SET_MENULIST, GET_MENULIST, REMOVE_MENULIST } from '../../utils/menuList'

// 引入路由
import { constantRoutes, asyncRoute, anyRoute } from '../../router/routes'
import * as _ from "lodash";
import router from "../../router";

// 筛选出当前用户的路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
    return asyncRoute.filter((item: any) => {
        if (routes.includes(item.path)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}

// 数组去重
function uniqueByFilter(array: any) {
    return array.filter((item: any, index: any, self: any) => self.indexOf(item) === index);
}

function getRolePath(routesArr: any) {
    let rolePathArr: any = []
    routesArr.forEach((item: any) => {
        if (item.pagePath) {
            rolePathArr.push(item.pagePath)

        }
        if (item.childMenuList.length > 0) {
            rolePathArr.push(item.pagePath)
            item.childMenuList.forEach((item: any) => {
                if (item.pagePath) {
                    rolePathArr.push(item.pagePath)
                }
            })
        }
    })
    return rolePathArr
}


// 第一个参数：小仓库名字 第二个参数：小仓库配置对象
let useUserStore = defineStore("user", {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            menuRoutes: constantRoutes,
            username: '',
            avatar: '',
            user: {},
            menuList: GET_MENULIST()
        }
    },
    actions: {
        // 用户登录的方法
        async userLogin(data: loginFormData) {
            // 登录请求
            let result: loginResponseData = await reqLogin(data)
            if (result.code == 20000) {
                this.token = result.data.token
                // this.token = (result.data.token as string)
                // 获取当前角色的 路由路径
                let rolePath = uniqueByFilter(getRolePath(result.data.menuList))
                // 计算当前用户需要展示的异步路由
                let userRoute = filterAsyncRoute(_.cloneDeep(asyncRoute), rolePath)
                this.menuRoutes = [...constantRoutes, ...userRoute, anyRoute];
                // 追加动态路由 和任意路由
                [...userRoute, anyRoute].forEach((route: any) => {
                    router.addRoute(route)
                })

                SET_MENULIST(result.data.menuList)
                SET_TOKEN(result.data.token as string)
                return 'ok'
            } else {
                return Promise.reject(new Error(result.msg))
            }
        },
        // 获取用户信息
        async userInfo() {
            let result: UserInfoResponseData = await reqUserInfo()
            if (result.code == 20000) {
                this.username = result.data.username as string
                this.avatar = result.data.avatarUrl as string
                this.user = result.data

                return 'ok'

            } else {
                return Promise.reject(new Error(result.msg))
            }
        },
        // 退出登录
        async userLoginout() {
            let result = await reqLoginOut()
            if (result.code == 20000) {
                this.username = ''
                this.avatar = ''
                this.token = ''
                REMOVE_TOKEN()
                REMOVE_MENULIST()
            }
        }
    },
    getters: {

    }
})
export default useUserStore